package com.example.myblog01.service.impl;

import com.example.myblog01.dao.TagServiceDao;
import com.example.myblog01.pojo.Tag;
import com.example.myblog01.service.TagService;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class TagSserviceimpl implements TagService {

    @Autowired
    private TagServiceDao tagServiceDao;

    @Transactional
    @Override
    public Tag savetag(Tag tag) {
        return tagServiceDao.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagServiceDao.getById(id);
    }

    @Transactional
    @Override
    public Tag getTagByName(String name) {
        return tagServiceDao.findTagByName(name);
    }

    @Transactional
    @Override
    public Page<Tag> ListTag(Pageable pageable) {
        return tagServiceDao.findAll(pageable);
    }

    @Transactional
    @Override
    public List<Tag> listTag() {
        return tagServiceDao.findAll();
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagServiceDao.findById(id).orElse(null);

        if (t == null) {
            try {
                throw new NotFoundException("不存在");
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
        }
//        否则更新数据库
        BeanUtils.copyProperties(tag, t);
        return tagServiceDao.save(t);
    }

    @Override
    public List<Tag> listTag(String ids) {
//        查询多个id对应的值 返回List
        return tagServiceDao.findAllById(convertToList(ids));
    }

    //    将上面的List转换为数组
    private List<Long> convertToList(String ids) {
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            String[] idarray = ids.split(",");
            for(int i = 0; i < idarray.length; i++) {
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Transactional
    @Override
    public void deletetag(Long id) {
        tagServiceDao.deleteById(id);
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        return tagServiceDao.findTop(PageRequest.of(0,size,Sort.by(Sort.Direction.DESC, "blogs.size")));
    }



}
